package rc.work.module.bpm.service.problem.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Component;
import rc.work.module.bpm.api.event.BpmProcessInstanceStatusEvent;
import rc.work.module.bpm.api.event.BpmProcessInstanceStatusEventListener;
import rc.work.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import rc.work.module.bpm.controller.admin.problem.vo.Node;
import rc.work.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailReqVO;
import rc.work.module.bpm.controller.admin.task.vo.instance.BpmApprovalDetailRespVO;
import rc.work.module.bpm.dal.dataobject.problem.ProblemGroupDO;
import rc.work.module.bpm.dal.mysql.problem.ProblemGroupMapper;
import rc.work.module.bpm.enums.task.BpmTaskStatusEnum;
import rc.work.module.bpm.service.definition.BpmProcessDefinitionService;
import rc.work.module.bpm.service.problem.ProblemService;
import rc.work.module.bpm.service.problem.ProblemServiceImpl;
import rc.work.module.bpm.service.task.BpmProcessInstanceService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static rc.work.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Component
public class ProblemApproListener extends BpmProcessInstanceStatusEventListener {

    @Resource
    private ProblemService problemService;
    @Resource
    private ProblemGroupMapper problemGroupMapper;

    @Resource
    private BpmProcessDefinitionService processDefinitionService;
    @Resource
    private BpmProcessInstanceService processInstanceService;

    @Override
    protected String getProcessDefinitionKey() {
        return ProblemServiceImpl.PROCESS_KEY_WTSH;
    }

    @Override
    protected void onEvent(BpmProcessInstanceStatusEvent event) {
        Integer status = event.getStatus();
        String businessKey = event.getBusinessKey();
        String[] split = businessKey.split("_");
        String problemBpmId = split[0];
        String userId  = split[1];
        String approStr = split[2];
        if(BpmTaskStatusEnum.APPROVE.getStatus().equals(status)){
            // 审批通过
            //继续回溯


            //自办完成之后 需要原路返回
            // 获得所有流程节点
            LambdaQueryWrapper<ProblemGroupDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProblemGroupDO::getProblemBpmId, problemBpmId);
            queryWrapper.last("limit 1");
            ProblemGroupDO problemGroupDO = problemGroupMapper.selectOne(queryWrapper);
            List<Node> bpmActivity = problemService.getBpmActivity(problemGroupDO.getGroupId());
            // 找到最后一个节点
            int size = bpmActivity.size();
            for (int i = size-1; i>=0; i--) {
                if(bpmActivity.get(i).getUserId().equals(getLoginUserId().toString())){
                    // 找到这个节点的前一个节点
                    if(i==0){
                        //表示自办自销了  不需要做任何操作
                        break;
                    }else{
                        Node preNode = bpmActivity.get(i-1);

                        ProcessDefinition activeProcessDefinition = processDefinitionService.getActiveProcessDefinition(ProblemServiceImpl.PROCESS_KEY_WTSH);
                        BpmApprovalDetailRespVO approvalDetail = processInstanceService.getApprovalDetail(getLoginUserId(), new BpmApprovalDetailReqVO() {{
                            setProcessDefinitionId(activeProcessDefinition.getId());
                        }});

                        List<BpmApprovalDetailRespVO.ActivityNode> activityNodes = approvalDetail.getActivityNodes();

                        Map<String, List<Long>> startUserSelectAssignees = new HashMap<>();
                        activityNodes.forEach(activityNode -> {
                            if(activityNode.getNodeType().equals(11)){
                                startUserSelectAssignees.put(activityNode.getId(), List.of(Long.parseLong(preNode.getUserId())));
                            }
                        });

                        // 给这个账号发起一个回溯审核代办
                        // 发起 BPM 流程
                        Map<String, Object> processInstanceVariables = new HashMap<>();
                        processInstanceVariables.put("type", 1);
                        processInstanceVariables.put("dataId", problemBpmId);
                        String processInstanceId = processInstanceService.createProcessInstance(getLoginUserId(),
                                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(ProblemServiceImpl.PROCESS_KEY_WTSH)
                                        // 这里采用拼接方式 后面的1 是为了让用户判断是否需要审核
                                        .setVariables(processInstanceVariables).setBusinessKey(problemBpmId+"_"+preNode.getUserId()+"_appro")
                                        .setStartUserSelectAssignees(startUserSelectAssignees));
                    }


                }

            }


        }

        if(BpmTaskStatusEnum.REJECT.getStatus().equals(status)){

        }
        if (BpmTaskStatusEnum.CANCEL.getStatus().equals(status)) {

        }
        if (BpmTaskStatusEnum.RETURN.getStatus().equals(status)) {

        }
    }

}
